package com.example.springboot.controller;

import cn.hutool.core.collection.CollUtil;
import com.example.springboot.common.Result;
import com.example.springboot.controller.request.CategoryPageRequest;
import com.example.springboot.entity.Category;
import com.example.springboot.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:CateGoryController
 * Package:com.example.springboot.controller
 * Description:
 *
 * @Author: Gao
 * @Create: 2023/2/6 - 14:35
 */
@RestController
@RequestMapping( "/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    @GetMapping("/")
    public Result list(){
        List<Category> categories = categoryService.list();
        return Result.success(categories);
    }

    @GetMapping("/tree")
    public Result tree(){
        List<Category> list = categoryService.list();
        //返回的data为树形结构
        return Result.success(createTree(null, list));
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") int id){
        Category category = categoryService.getById(id);
        return Result.success(category);
    }

    @GetMapping("/page")
    public Result page(CategoryPageRequest pageRequest){
        Object page = categoryService.page(pageRequest);
        return Result.success(page);
    }

    @PutMapping("/")
    public Result update(@RequestBody Category category){
        categoryService.update(category);
        return Result.success();
    }

    @PostMapping("/")
    public Result save(@RequestBody Category category){
        categoryService.save(category);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable int id){
        categoryService.deleteById(id);
        return Result.success();
    }

    /**
     * 创建树形结构
     * @param pid
     * @param categories
     * @return
     */
    private List<Category> createTree(Integer pid, List<Category> categories){
        List<Category> treeList = new ArrayList<>();
        for (Category category : categories) {
            if (pid == null) {
                if (category.getPid() == null) {
                    //第一级节点
                    treeList.add(category);
                    category.setChildren(createTree(category.getId(), categories));
                }
            } else {
                //其他级节点
                if (pid.equals(category.getPid())) {
                    treeList.add(category);
                    category.setChildren(createTree(category.getId(), categories));
                }
            }
            if(CollUtil.isEmpty(category.getChildren())){
                //保证最底层的children为null，而非[]，否则在选择时无最底层的节点
                category.setChildren(null);
            }
        }
        return treeList;
    }


}
